import urllib
from socket import *
import DataParse
from urllib.request import urlopen
from test import get_test_data
import time

class Manager():
    def __init__(self):
        self.current_string_data = ""
        self.dir_data = {}

    def get_current_string_data(self):
        return self.current_string_data

    def append_current_string_data(self, data):
        self.current_string_data = self.current_string_data + data

    def clear(self):
        self.current_string_data = ""

    def check(self):
        record = []
        for key in self.dir_data.keys():
            if len(self.dir_data[key]) == 3:
                string = ""
                for item in self.dir_data[key]:
                    string = string + '\n' + item
                splits = string.split("\n")
                data = []
                for item in splits:
                    if len(item)!=0 and item!='\n' and item!='\r':
                        data.append(item + '\n')
                record.append(key)
                data.append(' ')
                print("字典长度{0},长度{1},送往解析{2}".format(len(self.dir_data.keys()),len(data),key))
                print("送检时间点{0}，".format(int(round(time.time() * 1000))))
                parse_data(data)
        for item in record:
            self.dir_data.pop(item)


manager = Manager()
parse_data_manager = DataParse.ParseDataManager()


def writeToFile(list_data):
    with open("ceshi" + '.txt', 'a+') as file:
        file.write(list_data)


def transfer(data):
    return data.replace(b'\r', b'\n').decode('GBK')


def split(data):
    message = data.split(b'\x1c\r')
    data = message[-1]
    return message[:-1], data


def ack_message(message):
    if not message:
        return []
    res = []
    for sentence in message:
        string = transfer(sentence)
        ack = ''
        meta = string.split('\n')[0].split('|')
        for i in range(8):
            ack = ack + meta[i] + '|'
        ack = ack + 'ACK|' + meta[9] + '|' + 'P' + meta[11] + '\rMSA|AA|' + meta[9] + '\r\x1c\r'
        res.append(ack.encode())
    return res

    # 解析数据


def parse_data(list_data):
    # print("类型测试", type(list_data))
    parse_data_manager.clear()
    result = DataParse.parse_data(list_data, parse_data_manager, flow_data=True)
    print("送检获取结果时间点{0}，".format(int(round(time.time() * 1000))))
    #writeToFile(result)
    forward_to_go(result)


# 将数据转发到go端口
def forward_to_go(json_datas):
    url = 'http://42.193.110.73/v1/recv'
    print("发送数据类型{0}".format(type(json_datas)))
    data = bytes(json_datas, 'utf8')
    response=urllib.request.urlopen(url=url, data=data)
    print("返回{0}".format(response.read().decode('utf8')))
    # else:
    #     for item in json_datas:
    #         data = bytes(item, 'utf8')
    #         urllib.request.urlopen(url=url, data=data)


def parse_and_forward(msg_t="", is_end=False):
    print("片段接受时间点{0}".format(int(round(time.time()*1000))))
    if is_end:
        #先解析这个数据片段
        fragments_temp = manager.current_string_data.split('')
        record = []
        for index in range(0, len(fragments_temp)):
            if fragments_temp[index] == "" or fragments_temp[index] == "\n" or fragments_temp[index] == "\r" or \
                    fragments_temp[index] == " ":
                record.append(index)
        for item in record:
            fragments_temp.pop(item)

        print("数据带有数据片段{0}".format(len(fragments_temp)))
        for item in fragments_temp:
            index = item.find("20211")
            time_temp = item[index:index + 14]
            if index > 0 and time_temp in manager.dir_data.keys():
                manager.dir_data[time_temp].append(item + '')
            else:
                manager.dir_data[time_temp] = []
                manager.dir_data[time_temp].append(item + '')
            manager.check()
        manager.clear()

        # index=manager.current_string_data.find("20211027")
        # print(type(index))
        # time=manager.current_string_data[index:index+14]
        # print("写入日期{0}".format(time))
        # writeToFile(manager.current_string_data)
        # writeToFile("\n-------------------------------{0}-----------------------------------\n".format(time))
        # manager.clear()
    else:
        manager.append_current_string_data(msg_t)


def main():
    host = ""  # 服务端ip
    port = 8102  # 服务端端口号
    buff_size = 2048
    addr = (host, port)
    feedback = 'N'
    buf = b''  # 设置缓冲区

    while True:
        tcp_cliSock = socket()  # 创建socket对象
        try:
            tcp_cliSock.bind(addr)
        except:
            print('监护仪连接失败')
            input('按Enter键退出')
            exit()
        tcp_cliSock.listen(5)
        connect, address = tcp_cliSock.accept()
        print('address:', address)
        while True:
            try:
                raw = connect.recv(buff_size)  # 读取消息
            except:
                tcp_cliSock.close()
                break
            buf = buf + raw
            msg, buf = split(buf)  # 将缓冲区数据分离
            if len(msg) == 0:
                parse_and_forward(is_end=True)
                continue

            for bit in msg:
                parse_and_forward(transfer(bit + b'\x1c\r'))
                # print('收到：\n', transfer(bit + b'\x1c\r'))
            if feedback == 'y' or feedback == 'Y':
                resp = ack_message(msg)  # 进行应答反馈
            else:
                resp = []
            if not resp:
                continue
            else:
                for s in resp:
                    # print('应答：', s)
                    connect.sendall(s)  # 反馈


def test():
    forward_to_go(get_test_data())


if __name__ == '__main__':
    main()
